<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-wrapper">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入角色名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="table-wrapper">
      <template #header>
        <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
        <el-button type="danger" :icon="Delete" :disabled="!selectedIds.length" @click="handleBatchDelete">
          批量删除
        </el-button>
      </template>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="roleList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="角色名称" prop="name" />
        <el-table-column label="角色编码" prop="code" />
        <el-table-column label="描述" prop="description" show-overflow-tooltip />
        <el-table-column label="状态" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="180" />
        <el-table-column label="操作" align="center" width="250">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Edit" @click="handleUpdate(row)">编辑</el-button>
            <el-button type="primary" link :icon="Setting" @click="handlePermission(row)">权限设置</el-button>
            <el-button type="danger" link :icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      :title="dialog.title"
      v-model="dialog.visible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="roleFormRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入角色描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      title="权限设置"
      v-model="permissionDialog.visible"
      width="600px"
      append-to-body
    >
      <el-tree
        ref="permissionTreeRef"
        :data="permissionList"
        :props="{ label: 'name', children: 'children' }"
        show-checkbox
        node-key="id"
        default-expand-all
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPermission">确 定</el-button>
          <el-button @click="permissionDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Setting } from '@element-plus/icons-vue'
import { getRoleList as getRolesList, createRole, updateRole, deleteRole, getRolePermissions, updateRolePermissions } from '@/api/system'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const roleList = ref([])
const total = ref(0)
const selectedIds = ref([])

// 对话框
const dialog = reactive({
  visible: false,
  title: ''
})

// 权限对话框
const permissionDialog = reactive({
  visible: false,
  roleId: undefined
})

// 表单
const roleFormRef = ref()
const form = reactive({
  id: undefined,
  name: '',
  code: '',
  description: '',
  status: 'active'
})

// 权限树
const permissionTreeRef = ref()
const permissionList = ref([
  {
    id: 1,
    name: '系统管理',
    children: [
      { id: 11, name: '用户管理' },
      { id: 12, name: '角色管理' },
      { id: 13, name: '菜单管理' }
    ]
  },
  {
    id: 2,
    name: '业务管理',
    children: [
      { id: 21, name: '订单管理' },
      { id: 22, name: '商品管理' },
      { id: 23, name: '客户管理' }
    ]
  }
])

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]+$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 获取角色列表
const getRoleList = async () => {
  try {
    loading.value = true
    
    const params = {
      page: queryParams.pageNum,
      size: queryParams.pageSize,
      name: queryParams.name,
      status: queryParams.status
    }
    
    // 调用真实API获取角色列表  
    const response = await getRolesList(params)
    
    if (response.code === 200) {
      roleList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getRoleList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.status = ''
  handleQuery()
}

// 选择项变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 新增角色
const handleAdd = () => {
  dialog.title = '新增角色'
  dialog.visible = true
  Object.assign(form, {
    id: undefined,
    name: '',
    code: '',
    description: '',
    status: 'active'
  })
}

// 修改角色
const handleUpdate = (row) => {
  dialog.title = '修改角色'
  dialog.visible = true
  Object.assign(form, row)
}

// 删除角色
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认要删除该角色吗？', '警告', {
      type: 'warning'
    })
    
    const res = await deleteRole(row.id)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      getRoleList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的角色')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确认要删除选中的 ${selectedIds.value.length} 个角色吗？`, '警告', {
      type: 'warning'
    })
    
    // 批量删除API调用
    const promises = selectedIds.value.map(id => deleteRole(id))
    await Promise.all(promises)
    
    ElMessage.success('批量删除成功')
    getRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 权限设置
const handlePermission = async (row) => {
  permissionDialog.roleId = row.id
  permissionDialog.visible = true
  
  try {
    const res = await getRolePermissions(row.id)
    if (res.code === 200) {
      setTimeout(() => {
        permissionTreeRef.value.setCheckedKeys(res.data || [])
      }, 100)
    }
  } catch (error) {
    ElMessage.error('获取角色权限失败')
  }
}

// 提交权限设置
const submitPermission = async () => {
  try {
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    
    const res = await updateRolePermissions(permissionDialog.roleId, {
      permissionIds: [...checkedKeys, ...halfCheckedKeys]
    })
    
    if (res.code === 200) {
      ElMessage.success('权限设置成功')
      permissionDialog.visible = false
    }
  } catch (error) {
    ElMessage.error('权限设置失败')
  }
}

// 提交表单
const submitForm = async () => {
  try {
    const valid = await roleFormRef.value.validate()
    if (!valid) return
    
    const api = form.id ? updateRole : createRole
    const res = await api(form)
    
    if (res.code === 200) {
      ElMessage.success(form.id ? '修改成功' : '新增成功')
      dialog.visible = false
      getRoleList()
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getRoleList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getRoleList()
}

// 初始化
onMounted(() => {
  getRoleList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-wrapper {
    margin-bottom: 20px;
  }
  
  .table-wrapper {
    :deep(.el-card__header) {
      padding: 10px 20px;
    }
  }
  
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
}
</style> 